/*
 * This file is part of algowala.
 *
 * algowala is copyright (c) 2012 Jagannathan Sampath <algowala@jagernot.com>
 *
 * algowala is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * algowala is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with algowala.  If not, see <http://www.gnu.org/licenses/>.
 *
*/

#include "udp_server.h"
#include "ansi_color_codes.h"
#include <string.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fcntl.h>
using namespace std;

extern std::string APP_NAME;

udp_server::udp_server (int port) {
  
  // server boilerplate
  sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons (port);
  server.sin_addr.s_addr = INADDR_ANY;
  bzero(&(server.sin_zero), 8);
  
  sock = socket (AF_INET, SOCK_DGRAM, 0); // create socket
  if (sock == -1) {
    cout << FAIL << "!!! couldnt open UDP socket !!!" << endl;
  } else {
    fcntl(sock, F_SETFL, O_NONBLOCK); // make socket non-blocking
  }
  
  // bind socket to port
  if (bind (sock, (sockaddr *) &server, sizeof (sockaddr)) == -1) {
    cout << FAIL << "couldnt setup UDP server to listen at port " << port << endl;
    perror ("bind");
    sock = -1;
  } else {
    cout << PASS << APP_NAME << " UDP server waiting for commands at port " << port << std::endl;
  }

}

void udp_server::start () {
  if (sock != -1) {
    quit_thread = 0;
    pthread_create (&thrd, 0, udp_server::run, this);
  }
}

void* udp_server::run (void* arg) {
  
  // for recieving data
  static const int recv_buf_size = 1024;
  char recv_buf [recv_buf_size];
  int bytes_read;

  udp_server* srv = static_cast<udp_server*> (arg);
  sockaddr_in client;
  socklen_t len = sizeof (sockaddr);
  
  while (quit_thread == 0) {
    // socket is non-blocking so return if nothing to read
    //
    bytes_read = recvfrom (srv->sock, recv_buf, recv_buf_size, 0, (sockaddr *) &client, &len); 
    if (bytes_read > 0) {
      cout << recv_buf << endl;
      recv_buf [bytes_read] = '\0';
      srv->push (-1, recv_buf);
    }
    usleep (1);
  }
    
  return 0;
  
}

void udp_server::stop () {
  
  if (sock != -1) {
    udp_server::quit_thread = 1;
    pthread_join (thrd, 0);
    cout << PASS << APP_NAME << " UDP server is now closed" << endl;
  }
  
}
